//
//  ALEmoticonManager.swift
//  键盘-表情处理
//
//  Created by Miaoyang on 16/4/24.
//  Copyright © 2016年 Miaoyang. All rights reserved.
//

import UIKit

///一页显示的数量
let numberOfPage = 20

class ALEmoticonManager: NSObject {
   
   ///定义一个单利
    static let sharedManager:ALEmoticonManager = ALEmoticonManager()
    /// 外界通过这个属性来访问 所有表情包, 只会加载一次
    lazy var packageModels: [ALEmoticonPackageModel] = self.loadPackages()
    
    /// 表情包模型是从bundle里面加载出来的,bundle是在磁盘上.如果多次加载是比较耗性能,而且bundle加载出来是不会变,只需要加载一次
    /// 加载所有表情包
    private func loadPackages() -> [ALEmoticonPackageModel] {
        // 加载最近表情包, 默认表情包里面没有表情,是一个空数组
        let recentPackage = ALEmoticonPackageModel(id: "", group_name_cn: "最近", emoticons: [ALEmoticonModel]())
        
        let defaultPackage = loadPackage("com.sina.default")
        let emojiPackage = loadPackage("com.apple.emoji")
        let lxhPackage = loadPackage("com.sina.lxh")
        
        return [recentPackage, defaultPackage, emojiPackage, lxhPackage]
    }
    
    /// 加载表情包
    ///
    /// - parameter id: 表情包文件夹名称
    /// 返回表情包模型
    private func loadPackage(id: String) -> ALEmoticonPackageModel {
        // 解析id文件夹下的info.plist
        // info.plist的路径 = Emoticons.bundle的路径/id/info.plist
        let EmoticonsBundlePath = NSBundle.mainBundle().pathForResource("Emoticons", ofType: "bundle")!
        //        print("EmoticonsBundlePath: \(EmoticonsBundlePath)")
        let infoPath = EmoticonsBundlePath + "/" + id + "/" + "info.plist"
        print("infoPath: \(infoPath)")
        
        let infoDict = NSDictionary(contentsOfFile: infoPath)!
        
        //        print("info的内容: \(infoDict)")
        // 解析内容
        /// 表情包名称
        let group_name_cn = infoDict["group_name_cn"] as! String
        
        var emoitcons = [ALEmoticonModel]()
        
        /// 表情数组里面存放的是字典
        if let emoticonsArray = infoDict["emoticons"] as? [[String: String]] {
            //遍历数组,获取里面的字典,字典转模型
            for dict in emoticonsArray {
                // 表情字典转表情模型
                let model = ALEmoticonModel(dict: dict)
                emoitcons.append(model)
            }
        }
        
        // 创建表情包
        return ALEmoticonPackageModel(id: id, group_name_cn: group_name_cn, emoticons: emoitcons)
    }
}
